<template>
  <section class="main">
    <input
      id="toggle-all"
      :checked="isAllDone ? todoList.length > 0 : false"
      @change="changeAllTodoStatus(!isAllDone)"
      class="toggle-all"
      type="checkbox"
    />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <!-- :class="{ completed: item.done }" -->
      <li
        class="todo"
        :class="{ completed: item.done }"
        v-for="(item, index) in todoList"
        :key="item.id"
      >
        <div @dblclick="changeIsEdit(index)" v-show="!item.isEdit">
          <input
            @change="changeTodoStatus(index, $event)"
            class="toggle"
            type="checkbox"
            :checked="item.done"
          />
          <label>{{ item.text }}</label>
          <button class="destroy" @click="del(index)"></button>
        </div>
        <input
          class="edit"
          :value="item.text"
          v-show="item.isEdit"
          type="text"
          @keyup.enter="endEdit(index, $event)"
          @blur="endEdit(index, $event)"
        />
      </li>
    </ul>
  </section>
</template>

<script lang="ts" setup>
import { defineProps } from 'vue';
import useTodoStore from '../stores/todo';
import type { TodoListType } from '@/hooks/model/todoModel';
let store = useTodoStore();

// defineProps({
//   todoList: {
//     type: Array,
//     default: [],
//   },
//   isAllDone: {
//     type: Boolean,
//     default: false,
//   },
// });

withDefaults(
  defineProps<{
    todoList: TodoListType;
    isAllDone: boolean;
  }>(),
  {
    todoList: () => [],
    isAllDone: false,
  }
);

const del = (idx: number) => {
  store.del(idx);
};
const changeTodoStatus = (idx: number, e: Event) => {
  const inputEl = e.target as HTMLInputElement;
  store.changeTodoStatus(idx, inputEl.checked);
};
const changeAllTodoStatus = (flag: boolean) => {
  store.changeAllTodoStatus(flag);
};
const changeIsEdit = (index: number) => {
  store.changeIsEdit(index);
};
const endEdit = (idx: number, e:  KeyboardEvent|FocusEvent) => {
  const inputEl = e.target as HTMLInputElement;
  store.endEdit(idx, inputEl.value);
};
</script>
